package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.common.RedisConst;
import com.itheima.health.dao.*;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.*;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@DubboService
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    UserRoleMapper userRoleMapper;


    /**
     * @Author: guodong
     * @Date: 11:49 2021/2/23
     * @Parms [username]
     * @ReturnType: com.itheima.health.pojo.User
     * @Description: 根据用户名查询用户
     */
    @Override
    public User findUserByName(String username) {
        //不使用tk
        //return userMapper.findUserByName(username);
        //使用tk完成查询
        User user = new User();
        user.setUsername(username);
        User user1 = userMapper.selectOne(user);

        //查询roles
        Set<Role> roles = roleMapper.findByUserId(user1.getId());
        user1.setRoles(roles);

        //查询permission
        for (Role role : roles) {
            Set<Permission> permissions = permissionMapper.findByRoleId(role.getId());
            role.setPermissions(permissions);
        }

        return user1;
    }


    /***
     * @Author: jay
     * @Date: 20:07 2021/3/5
     * @Params [type, telephone, validateCode]
     * @ReturnType: void
     * @Description: 验证码-登录
     */
    @Override
    public boolean login(String type, String telephone, String validateCode) {
        String code = (String) redisTemplate.boundValueOps(RedisConst.VALIDATE_CODE_PRE + type + "_" + telephone).get();
        assert code != null;
        if (code.equals(validateCode)) {
            return true;
        }
        return false;
    }


    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        if (queryPageBean.getQueryString() != null) {
            criteria.orLike("username", "%" + queryPageBean.getQueryString() + "%");
            criteria.orLike("telephone", "%" + queryPageBean.getQueryString() + "%");
        }
        Page<User> page = (Page<User>) userMapper.selectByExample(example);
        long total = page.getTotal();
        List<User> userList = page.getResult();
        return new PageResult(total, userList);
    }

    @Override
    public User findById(Integer id) {
        User checkItem = userMapper.selectByPrimaryKey(id);
        return checkItem;
    }

    /**
     * @Author: lenovo
     * @Date: 14:38 2021/5/8
     * @Parms [user, roleIds]
     * @ReturnType: void
     * @Description: 编辑用户
    */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(User user, Integer[] roleIds) {
        if (user.getPassword()!=null&& !user.getPassword().isEmpty()){
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String pwd = encoder.encode(user.getPassword());
            user.setPassword("{bcrypt}"+pwd);
        }
        userMapper.updateByPrimaryKeySelective(user);
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRoleMapper.delete(userRole);
        for (Integer roleId : roleIds) {
            userRole.setRoleId(roleId);
            userRoleMapper.insertSelective(userRole);
        }
    }


    @Override
    @Transactional
    public void delete(Integer id) {
        UserRole userRole = new UserRole();
        userRole.setUserId(id);
        userRoleMapper.delete(userRole);
        userMapper.deleteByPrimaryKey(id);
    }

    /**
     * @Author: jay
     * @Date: 9:25 2021/3/10
     * @Params []
     * @ReturnType: java.util.List<com.itheima.health.pojo.Menu>
     * @Description: 获取登录用户菜单
     */
    @Override
    public List<Menu> getMenuList(String username) {
        //根据用户名获取id
        User user = new User();
        user.setUsername(username);
        User selectOne = userMapper.selectOne(user);
        //根据用户id获取父菜单项集合
        List<Menu> menuList = menuMapper.getParentMenu(selectOne.getId());
        for (Menu menu : menuList) {
            List<Menu> childrenMenus = menuMapper.getChildrenMenu(menu.getId());
            menu.setChildren(childrenMenus);
        }
        return menuList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(Integer[] rolesIds, User user) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String pwd = encoder.encode(user.getPassword());
        user.setPassword("{bcrypt}"+pwd);
        userMapper.insertSelective(user);
        //2.维护中间关联关系表
        for (Integer rolesId : rolesIds) {
            UserRole userRole = new UserRole();
            userRole.setRoleId(rolesId);
            userRole.setUserId(user.getId());
            userRoleMapper.insertSelective(userRole);
        }
    }

    /**
     * @Author: jay
     * @Date: 12:30 2021/3/12
     * @Params [id]
     * @ReturnType: java.util.List<java.lang.Integer>
     * @Description: 用户-查询角色id
     */
    @Override
    public List<Integer> findRoleIdsById(Integer id) {
        UserRole userRole = new UserRole();
        userRole.setUserId(id);
        List<UserRole> userRoleList = userRoleMapper.select(userRole);
        log.info("UserServiceImpl中data{}",userRoleList);
        List<Integer> roleIds = new ArrayList<>();
        for (UserRole role : userRoleList) {
            roleIds.add(role.getRoleId());
        }
        return roleIds;
    }
}
